﻿using System;
using System.ComponentModel;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Collections.ObjectModel;
using System.Net;
using System.Collections;
using System.IO.IsolatedStorage;
using System.Xml.Serialization;
using Microsoft.Phone.Shell;
using System.IO;


namespace CanalDeNoticiasMSDNv4.ViewModels
{
    public class MainViewModel : ViewModelBase
    {
        public const string _spain = "http://channel9.msdn.com/Blogs/channel9spain/RSS";
        public const string _noticiasLink = "http://www.microsoft.com/spain/msdn/rss/noticias.xml";
        public const string _articulosLink = "http://www.microsoft.com/spain/msdn/rss/articulos.xml";

        public DateTime? LastRefresh { get; set; }


        bool[] _loading = new bool[3];

        public event EventHandler IsLoadingChanged;

        public bool IsLoading
        {
            get { return _loading[0] || _loading[1] || _loading[2]; }
        }

        private void startLoad()
        {
            _loading[0] = _loading[1] = _loading[2] = true;
            if (IsLoadingChanged != null)
                IsLoadingChanged(this, EventArgs.Empty);
        }

        private void endLoad(int index)
        {
            _loading[index] = false;
            if (!IsLoading && IsLoadingChanged != null)
            {
                IsLoadingChanged(this, EventArgs.Empty);
            }
        }

        public MainViewModel()
        {
            Videos = new SuspendableObservableCollection<ElementoEntradaVideo>();
            Noticias = new SuspendableObservableCollection<ElementoEntradaRss>();
            Articulos = new SuspendableObservableCollection<ElementoEntradaRss>();
        }

        public SuspendableObservableCollection<ElementoEntradaVideo> Videos
        {
            get;
            private set;
        }

        public SuspendableObservableCollection<ElementoEntradaRss> Noticias
        {
            get;
            private set;
        }

        public SuspendableObservableCollection<ElementoEntradaRss> Articulos
        {
            get;
            private set;
        }

        bool _error;
        public void LoadData()
        {
            startLoad();

            fillVideos(_spain);
            fillRss(_articulosLink, Articulos);
            fillRss(_noticiasLink, Noticias);
        }

        private void fillVideos(string rssUrl)
        {
            HttpWebRequest r = HttpWebRequest.CreateHttp(rssUrl);

            r.BeginGetResponse((e) =>
                {
                    if (e.IsCompleted)
                    {
                        try
                        {
                            var request = (HttpWebRequest)e.AsyncState;
                            using (WebResponse response = request.EndGetResponse(e))
                            {
                                using (Stream stream = response.GetResponseStream())
                                {
                                    List<ElementoEntradaVideo> elements;

                                    using (StreamReader rdr = new StreamReader(stream))
                                    {
                                        char[] buffer = new char[1024];
                                        StringBuilder bldr = new StringBuilder();
                                        int length = 0;
                                        while ((length = rdr.Read(buffer, 0, 1024)) > 0)
                                        {
                                            bldr.Append(buffer, 0, length);
                                        }
                                        elements = ElementoEntradaVideo.GetElements(bldr.ToString());
                                    }

                                    System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() =>
                                    {
                                        try
                                        {
                                            fillVideosList(elements);
                                        }
                                        finally
                                        {

                                            endLoad(0);
                                        }
                                    });
                                }

                            }
                        }
                        catch (WebException ex)
                        {
                            _lastError = ex.Status;
                            System.Windows.Deployment.Current.Dispatcher.BeginInvoke(
                                () => endLoad(0));
                        }
                    }
                }, r);
        }

        private void fillVideosList(List<ElementoEntradaVideo> elements)
        {
            this.Videos.Suspend();
            try
            {
                this.Videos.Clear();
                elements.ForEach((element) => this.Videos.Add(element));
            }
            finally
            {
                this.Videos.Resume();
            }
            this.LastRefresh = DateTime.Now;
        }

        WebExceptionStatus _lastError;

        private void fillRss(string rssUrl, SuspendableObservableCollection<ElementoEntradaRss> collection)
        {
            HttpWebRequest r = HttpWebRequest.CreateHttp(rssUrl);
            r.BeginGetResponse((e) =>
                {
                    if (e.IsCompleted)
                    {
                        var request = (HttpWebRequest)e.AsyncState;
                        try
                        {
                            using (WebResponse response = request.EndGetResponse(e))
                            {
                                using (Stream s = response.GetResponseStream())
                                {
                                    List<ElementoEntradaRss> elements;
                                    using (StreamReader rdr = new StreamReader(s))
                                    {
                                        char[] buffer = new char[1024];
                                        StringBuilder bldr = new StringBuilder();
                                        int length=0;
                                        while ((length=rdr.Read(buffer, 0, 1024)) > 0)
                                        {
                                            bldr.Append(buffer, 0, length);
                                        }

                                        elements = ElementoEntradaRss.GetElements(bldr.ToString());
                                    }
                                    

                                    System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() =>
                                    {
                                        try
                                        {
                                            fillRssList(collection, elements);
                                        }
                                        finally
                                        {
                                            if (collection == Noticias)
                                                endLoad(1);
                                            else
                                                endLoad(2);
                                        }

                                    });
                                }
                            }
                        }
                        catch (WebException ex)
                        {
                            _lastError = ex.Status;
                            if (collection == Noticias)
                                endLoad(1);
                            else
                                endLoad(2);
                        }

                    }
                }, r);
        }

        private void fillRssList(SuspendableObservableCollection<ElementoEntradaRss> collection, List<ElementoEntradaRss> elements)
        {
            collection.Suspend();
            try
            {
                collection.Clear();
                elements.ForEach((element) => collection.Add(element));
            }
            finally
            {
                collection.Resume();
            }
            this.LastRefresh = DateTime.Now;
        }

        const string keyName = "mainviewmodel";

        public void LoadFromIsolatedStorage()
        {
            using (IsolatedStorageFile file = IsolatedStorageFile.GetUserStoreForApplication())
            {
                if (file.FileExists(keyName))
                {
                    using (IsolatedStorageFileStream stream = file.OpenFile(keyName, System.IO.FileMode.Open))
                    {
                        XmlSerializer ser = new XmlSerializer(this.GetType());
                        MainViewModel model = (MainViewModel)ser.Deserialize(stream);
                        loadModel(model);
                    }
                }
            }
        }

        public void SaveToIsolatedStorage()
        {
            using (IsolatedStorageFile file = IsolatedStorageFile.GetUserStoreForApplication())
            {
                using (IsolatedStorageFileStream stream = file.OpenFile(keyName, System.IO.FileMode.Create))
                {
                    XmlSerializer ser = new XmlSerializer(this.GetType());
                    stream.Position = 0;
                    ser.Serialize(stream, this);
                }
            }
        }

        public void LoadFromState()
        {
            IDictionary<string, object> stateStore =
                    PhoneApplicationService.Current.State;
            if (stateStore.ContainsKey(keyName))
            {
                MainViewModel model = (MainViewModel)stateStore[keyName];
                loadModel(model);
            }
        }

        public void SaveToState()
        {
            IDictionary<string, object> stateStore =
                   PhoneApplicationService.Current.State;

            stateStore.Remove(keyName);
            stateStore.Add(keyName, this);
        }

        private void loadModel(MainViewModel model)
        {
            this.Articulos = model.Articulos;
            this.Noticias = model.Noticias;
            this.Videos = model.Videos;
            this.LastRefresh = model.LastRefresh;
        }
    }
}